/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.ThanhVienDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.*;
import java.util.ArrayList;
import java.util.Calendar;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Thanhvien;
import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

/**
 *
 * @author HoangLiem
 */
@WebServlet(name = "xuLyDangKy", urlPatterns = {"/xuLyDangKy"})
public class xuLyDangKy extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(1200);
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            String remoteAddr = request.getRemoteAddr();
            ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
            reCaptcha.setPrivateKey("6LdLl8gSAAAAAG5hc-V1YVietaHA6TeaX9fJAssW");
            String challenge = request.getParameter("recaptcha_challenge_field");
            String uresponse = request.getParameter("recaptcha_response_field");
            ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

            if (reCaptchaResponse.isValid()) {
                Thanhvien tv = new Thanhvien();
                if (request.getParameter("tenDangNhap") != null) {
                    String tenDangNhap = request.getParameter("tenDangNhap");
                    tv.setTenDangNhap(tenDangNhap);
                }
                if (request.getParameter("matKhau") != null) {
                    String matKhau = request.getParameter("matKhau");
                    try {
                        MessageDigest md5 = MessageDigest.getInstance("MD5");
                        md5.update(matKhau.getBytes());
                        BigInteger dis = new BigInteger(1, md5.digest());
                        //byte []dis=md5.digest();
                        matKhau = dis.toString(16);
                    } catch (NoSuchAlgorithmException e) {
                        System.out.print("Loi khong ma hoa duoc bang giai thuat MD5");
                    }
                    tv.setMatKhau(matKhau);
                }
                if (request.getParameter("tenThanhVien") != null) {
                    String tenThanhVien = request.getParameter("tenThanhVien");
                    tv.setTenThanhVien(tenThanhVien);
                }
                if (request.getParameter("hoThanhVien") != null) {
                    String hoThanhVien = request.getParameter("hoThanhVien");
                    tv.setHoThanhVien(hoThanhVien);
                }
                if (request.getParameter("email") != null) {
                    String email = request.getParameter("email");
                    tv.setEmail(email);
                }
                if (request.getParameter("dienThoai") != null) {
                    String dienThoai = request.getParameter("dienThoai");
                    tv.setDienThoai(dienThoai);
                }
                int ngay = 0;
                int thang = 0;
                int nam = 0;
                if (request.getParameter("ngay") != null) {
                    ngay = Integer.parseInt(request.getParameter("ngay"));
                }
                if (request.getParameter("thang") != null) {
                    thang = Integer.parseInt(request.getParameter("thang"));
                }
                if (request.getParameter("nam") != null) {
                    nam = Integer.parseInt(request.getParameter("nam"));
                }
                Calendar cal = Calendar.getInstance();
                cal.set(nam, thang, ngay);
                tv.setNgaySinh(cal.getTime());
                //Xu ly cac truong hop
                ArrayList<Thanhvien> dsThanhVien = ThanhVienDAO.getAllUsers();
                boolean tonTaiKhachHang = false;
                for (int i = 0; i < dsThanhVien.size(); i++) {
                    if (tv.getTenDangNhap().equals(dsThanhVien.get(i).getTenDangNhap())) {
                        tonTaiKhachHang = true;
                        break;
                    }
                }
                if (tonTaiKhachHang) {
                    request.setAttribute("ThongBao", "Tên đăng nhập đã tồn tại");
                    String url = "DangKyPage.jsp";
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                } else {
                    boolean kq = ThanhVienDAO.insertUser(tv);
                    if (kq == true) {
                        session.setAttribute("user", tv);
                        response.sendRedirect("thongBao.jsp");
                    } else {
                        request.setAttribute("ThongBao", "Ðăng ký thất bại, có lỗi trong quá trình thực thi");
                        String url = "dangkyPage.jsp";
                        RequestDispatcher rd = request.getRequestDispatcher(url);
                        rd.forward(request, response);
                    }
                }
            } else {
                //out.println("Answer is wrong");
                request.setAttribute("ThongBao", "Sai chuỗi xác nhận");
                String url = "dangkyPage.jsp";
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
